package conchmusic.conchmusicclient.activity;

import android.Manifest;
import android.app.Dialog;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import conchmusic.conchmusicclient.R;
import conchmusic.conchmusicclient.adapter.ManySelectAdapter;
import conchmusic.conchmusicclient.dao.ClientControl;
import conchmusic.conchmusicclient.dao.MyDBHelp;
import conchmusic.conchmusicclient.pojo.Song;
import conchmusic.conchmusicclient.pojo.SortMusic;
import conchmusic.conchmusicclient.util.DeleteSong;
import conchmusic.conchmusicclient.util.PinyinComparator;
import conchmusic.conchmusicclient.util.SongGetScanMusic;

public class ManySelectActivity extends AppCompatActivity {
   private List<Song> localMusics;
    private ListView manySelectListView;
    private ManySelectAdapter manySelectAdapter;
    private CheckBox checkBox;
    private int checknum=0;
    private List<Integer> checklist;
    private Dialog dialog;
    private Button okButton;
    private Button cancleButton;
    private CheckBox deleteLocalcheckBox;
    private List<Song> deleteList;
    private ClientControl clientControl;
    private MyDBHelp myDBHelp;
    private DeleteSong deleteSong;
    private selectMany select=selectMany.other;
    private int width;
    private int height;
    private PinyinComparator pinyinComparator;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("已选择0项");
        setContentView(R.layout.activity_many_select);
        int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
        WindowManager windowManager=(WindowManager)getSystemService(Context.WINDOW_SERVICE);
        width = windowManager.getDefaultDisplay().getWidth();//屏幕宽度
        height = windowManager.getDefaultDisplay().getHeight();
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        checklist=new ArrayList<Integer>();
        localMusics=new ArrayList<>();
        pinyinComparator=new PinyinComparator();
        manySelectListView=(ListView)findViewById(R.id.many_select_listView);
        localMusics=new ArrayList<>();
        myDBHelp=new MyDBHelp(this,"demon",null,1);
        clientControl=new ClientControl(myDBHelp);
        //读数据库
        localMusics=clientControl.findSongs(1);
        if(!localMusics.isEmpty()){
            localMusics=getIndexSong(localMusics);
        }
        for(int i=0;i<localMusics.size();i++){
            checklist.add(0);
        }
        manySelectAdapter=new ManySelectAdapter(ManySelectActivity.this,localMusics,checklist);
        manySelectListView.setAdapter(manySelectAdapter);
        manySelectListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ManySelectAdapter.ManyListItemView manyListItemView=(ManySelectAdapter.ManyListItemView) view.getTag();
                checkBox=(CheckBox)manyListItemView.checkBox;
                checkBox.toggle();
                if(checklist.get(position)==1){
                    checklist.set(position,0);
                    checknum--;
                }else if(checklist.get(position)==0){
                    checklist.set(position,1);
                    checknum++;
                }
                if(checknum==localMusics.size()){
                    select=selectMany.allSelect;
                }else if(checknum==0){
                    select=selectMany.noneSelect;
                }else{
                    select=selectMany.oneSelect;
                }
                invalidateOptionsMenu();

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflaterLocal=getMenuInflater();
        inflaterLocal.inflate(R.menu.many_select_actionbar,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        switch (select){
            case allSelect:
                menu.findItem(R.id.all_song_select).setVisible(false);
                menu.findItem(R.id.none_select_song).setVisible(true);
                setTitle("已选择"+Integer.toString(checknum)+"项");
                break;
            case noneSelect:
                menu.findItem(R.id.all_song_select).setVisible(true);
                menu.findItem(R.id.none_select_song).setVisible(false);
                setTitle("已选择"+Integer.toString(checknum)+"项");
                break;
            case oneSelect:
                menu.findItem(R.id.all_song_select).setVisible(true);
                menu.findItem(R.id.none_select_song).setVisible(false);
                setTitle("已选择"+Integer.toString(checknum)+"项");
                break;
            default:
                break;
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.all_song_select:
                for(int i=0;i<checklist.size();i++){
                    checklist.set(i,1);
                }
                checknum=localMusics.size();
                manySelectAdapter.notifyDataSetChanged();
                select=selectMany.allSelect;
                invalidateOptionsMenu();
                return true;
            case R.id.delete_many_song:
                dialog=new AlertDialog.Builder(ManySelectActivity.this).create();
                dialog.show();
                dialog.getWindow().setContentView(R.layout.local_sure_popup);
                WindowManager.LayoutParams insertParams = dialog.getWindow().getAttributes();
                insertParams.width = (int)(width*0.8);
                insertParams.height = (int)(height*0.4);
                dialog.getWindow().setAttributes(insertParams);
                okButton=(Button) dialog.getWindow().findViewById(R.id.dialog_ok);
                cancleButton=(Button) dialog.getWindow().findViewById(R.id.dialog_cancel);
                deleteLocalcheckBox=(CheckBox)dialog.getWindow().findViewById(R.id.check_delete_single_popup) ;
                okButton.setOnClickListener(sureDeleteListener);
                cancleButton.setOnClickListener(sureDeleteListener);
                deleteLocalcheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        deleteLocalcheckBox.setChecked(isChecked);
                    }
                });
                return true;
            case android.R.id.home:
                Intent upIntent = NavUtils.getParentActivityIntent(this);
                if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
                    TaskStackBuilder.create(this)
                            .addNextIntentWithParentStack(upIntent)
                            .startActivities();
                } else {
                    upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    NavUtils.navigateUpTo(this, upIntent);
                }
                return true;
            case R.id.none_select_song:
                for(int i=0;i<checklist.size();i++){
                    checklist.set(i,0);
                }
                checknum=0;
                manySelectAdapter.notifyDataSetChanged();
                select=selectMany.noneSelect;
                invalidateOptionsMenu();
            default:
                return super.onOptionsItemSelected(item);
        }
    }


    private View.OnClickListener sureDeleteListener=new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.dialog_ok:
                    deleteList=new ArrayList<Song>();
                    List<Integer> halfway=new ArrayList<>();
                    for(int i=0;i<checklist.size();i++){
                        if(checklist.get(i)==1){
                            deleteList.add(localMusics.get(i));
                            halfway.add(checklist.get(i));
                        }
                    }
                    if (deleteLocalcheckBox.isChecked()) {
                        //删除本地
                        for(Song song:deleteList){
                            clientControl.deleteOriginSong(song.getLocalSongId(),1);
                            deleteSong=new DeleteSong(song.getLocalSongUrl(),song.getLocalPictureUrl(),song.getLocalLyricUrl());
                            deleteSong.deleteSong();
                        }
                    } else {
                        //不删除本地deleteList
                        for(Song song:deleteList){
                            clientControl.deleteSong(song.getLocalSongId(),1);
                        }
                    }
                    checklist.removeAll(halfway);
                    localMusics.removeAll(deleteList);
                    manySelectAdapter.notifyDataSetChanged();
                    dialog.cancel();
                    break;
                case R.id.dialog_cancel:
                    dialog.cancel();
                    break;
            }
        }
    };
     enum selectMany{
        allSelect,noneSelect,oneSelect,other
    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        ManySelectActivity.this.finish();
    }
    public ArrayList<Song> getIndexSong(List<Song> songs){
        SongGetScanMusic songGetScanMusic=new SongGetScanMusic(songs);
        ArrayList<SortMusic> sortMusics=songGetScanMusic.getmSortList();
        ArrayList<Song> sortSongs=new ArrayList<>();
        Collections.sort(sortMusics,pinyinComparator);
        for(SortMusic sortMusic:sortMusics){
            sortSongs.add(sortMusic.getSong());
        }
        return sortSongs;
    }
}
